package security.servlet;

import java.io.IOException;
import java.math.BigInteger;

import java.security.PrivateKey;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Email.SendEmail;
import Encryption.Encryptor;
import Hash.Hashing;

import properties.Fixed;
import user.Reset;
import user.BID;
import user.User;
//import com.sun.org.apache.xml.internal.security.Init;

import db.ConnectionManager;

@SuppressWarnings("serial")
public class SecurityServlet extends HttpServlet {

	public static String encrypted;

	// public static Encryptor enc;
	@Override
	public void init() throws ServletException {
		try {
			Fixed.beforeInit();
			// enc = new Encryptor();
			ConnectionManager.init(Fixed.caption("DBURL"));
			System.out.println("eihh ba2a");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doPost(request, response);
	}

	@Override
	@SuppressWarnings({ "unused", "deprecation" })
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String errorMessage = null;
		// boolean vf_request = false;
		StringBuffer result = null;
		request.setCharacterEncoding("UTF-8");
		response.setContentType("application/text");
		response.setHeader("Cache-Control", "no-cache");
		String action = request.getParameter("action");

		System.out.println();
		try {
			if (action == null)
				;

			else {

				if (action.equals("login")) {
					System.out.println("login");
					String userName = request.getParameter("usrname");
					String pass = request.getParameter("passwd");

					User u = new User();
					u.setUserName(userName);
		
						u.load();
						pass = Encryptor.b2h(Hashing.getHash(pass,
								(u.getTimeStamp() + "").getBytes("UTF-8")));
						request.getSession().setAttribute("user",
								u.getUserName());
					

					if (pass.equals(u.getPassword())) {
						
						if (userName.equalsIgnoreCase("admin")) {
							User s = new User();
							try {
								ArrayList<User> users = s.loadAllUsers(false,null);
								request.setAttribute("table", users);
								request.getRequestDispatcher("/admin.jsp")
										.forward(request, response);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						} else {

							BID bid1 = new BID();
								bid1.load();
								ArrayList<BID> bids = BID.bids;
								request.setAttribute("bids", bids);
								request.getRequestDispatcher("/Bid.jsp")
										.forward(request, response);
						
						}
					} else {
						System.out.println(u.getPassword());
						System.out.println("Login Failed");
						request.setAttribute("login",
								"Login Failed, Please try again");

						request.getRequestDispatcher("/index.jsp").forward(
								request, response);
					}
					// request.getRequestDispatcher("/index.html").forward(request,
					// response);
				} else if (action.equals("register")) {
					String userName = request.getParameter("usrname");
					String pass = request.getParameter("passwd");
					String creditCard = request.getParameter("ccard");
					creditCard = new String(creditCard);
					String email = request.getParameter("email");
			
						if(userName.contains(" ")){
							request.setAttribute("register",
									"Username cannot contain spaces");

							request.getRequestDispatcher("/register.jsp").forward(
									request, response);
							return;
						}
					User u = new User();
					u.setPassword(pass);
					u.setCreditCardNumber(creditCard);
					u.setEmail(email);
					u.setUserName(userName);
					try {
						u.register();
						request.setAttribute("register",
								"Registeration successful");

						request.getRequestDispatcher("/index.jsp").forward(
								request, response);
						
					} catch (Exception e) {
						// TODO Auto-generated catch block
						request.setAttribute("register",
								"Username is already taken");

						request.getRequestDispatcher("/register.jsp").forward(
								request, response);
						e.printStackTrace();
					}
				} else if (action.equals("resetLink")) {
					String userName = request.getParameter("userName");
					User u = new User();
					Reset r = new Reset();
					r.setUserName(userName);
					u.setUserName(userName);
						if (u.load()) {
							r.resetLink();
							String Link = "http://localhost:8080/Security/Security?action=change&usr="
									+ r.getUserName() + "&r=" + r.getrKey();
							u.getUserEmail();
							String email = u.getEmail();
							SendEmail.sendEmail(email, Link);
							request.setAttribute("register",
									"A reset link has been sent to your email inbox");
							request.getRequestDispatcher("/index.jsp").forward(
									request, response);
						}
					
				} else if (action.equals("change")) {
					// checks
					String userName = request.getParameter("usr");
					String hashedKey = request.getParameter("r");
					Reset r = new Reset();
					r.setUserName(userName);
					r.setrKey(hashedKey);
						if (r.checkTimeStamp()) {
							System.out.println("tmam");
							request.getSession().setAttribute("Verified",
									"true");
							request.setAttribute("user", hashedKey);
							System.out.println("alyyy" + hashedKey);
							request.getRequestDispatcher("/changePassword.jsp")
									.forward(request, response);
						} else {
							System.out.println("hobaaa");
							request.setAttribute("Reset", "Link doesn't Exist");
							request.getRequestDispatcher("/index.jsp").forward(
									request, response);
						}
					

				} else if (action.equals("changePass")) {
					String userKey = request.getParameter("userKey");
					Reset r = new Reset();
					r.setrKey(userKey);
						if (r.deleteKey()) {
							User s = new User();
							s.setUserName(r.getUserName());
							s.setPassword(request.getParameter("passwd"));
							s.updatePassword();
							request.setAttribute("register",
									"Password changed successfully");
							request.getRequestDispatcher("/index.jsp").forward(
									request, response);

						} else {
							request.setAttribute("Reset", "Link doesn't Exist");
							request.getRequestDispatcher("/index.jsp").forward(
									request, response);
						}
					
				} else if (action.equals("BID")) {

					BID bid1 = new BID();
						bid1.load();
						ArrayList<BID> bids = BID.bids;
						request.setAttribute("bids", bids);
						request.getRequestDispatcher("/Bid.jsp").forward(
								request, response);
					

				} else if (action.equals("insertBid")) {
					String bidValue = request.getParameter("bidValue");
					BID bid1 = new BID();
					String userName = (String) request.getSession()
							.getAttribute("user");
					bid1.setName(userName);
					bid1.setBidValue(bidValue);
					if (userName == null) {
						request.setAttribute("Reset", "You are not logged in");
						request.getRequestDispatcher("/index.jsp").forward(
								request, response);
					} else {
							bid1.add();
							bid1.load();

						request.setAttribute("bids", BID.bids);
						request.getRequestDispatcher("/Bid.jsp").forward(
								request, response);
					}
				} else if (action.equals("logout")) {
					// if(!request.getSession().isNew())
					request.getSession().invalidate();

					request.getRequestDispatcher("/index.jsp").forward(request,
							response);
				} else if (action.equals("decryptPasswords")) {
					if ("admin".equalsIgnoreCase((String) request.getSession()
							.getAttribute("user"))) {
						BigInteger key =null;
						User s = new User();

						try{
						key = new BigInteger((String) request
								.getParameter("privateKey"));
						}catch(NumberFormatException e2){
							ArrayList<User> users = s.loadAllUsers(false,null);
							request.setAttribute("table", users);
							request.setAttribute("Reset", "only digits are allowed");
							request.getRequestDispatcher("/admin.jsp")
									.forward(request, response);
							return;
						}
						BigInteger privKey = Encryptor.readPrivateKeyFromFile();
						System.out.println(key);
						System.out.println(privKey);
						//PrivateKey privKey2  = Encryptor.readPrivateKeyFromFile("private1.key");

						//if (key.equals(privKey)) {
						try{
								ArrayList<User> users = s.loadAllUsers(true,key);
								request.setAttribute("table", users);
								request.setAttribute("register", "Creditcards decrypted");
								request.getRequestDispatcher("/admin.jsp")
										.forward(request, response);
						}catch(Exception e){
							ArrayList<User> users = s.loadAllUsers(false,null);
							request.setAttribute("table", users);
							request.setAttribute("Reset", "Wrong key");
							request.getRequestDispatcher("/admin.jsp")
									.forward(request, response);
						}
					/*	} else {
							ArrayList<User> users = s.loadAllUsers(false);
							request.setAttribute("table", users);
							request.setAttribute("Reset", "Wrong key");
							request.getRequestDispatcher("/admin.jsp")
									.forward(request, response);
						}*/

					} else {
						request.setAttribute("Reset", "You are not authorized");
						request.getRequestDispatcher("/index.jsp").forward(
								request, response);

					}

				}
			}

		} catch (Exception e) {
			request.setAttribute("Reset", "You are not authorized");
			request.getRequestDispatcher("/index.jsp").forward(
					request, response);
			e.printStackTrace();
		}

	}

	public static boolean checkKey(String HashedKey) throws SQLException,
			ClassNotFoundException {
		if (Reset.checkKey(HashedKey)) {
			return true;
		} else {
			return false;
		}
	}
}